<script setup>
import { ref, onMounted,reactive} from 'vue'
import {ElMessage,ElMessageBox} from "element-plus";
import {addConsultant, deleteConsultant, queryAllConsultant, updateConsultant} from "@/api/consultant.js";
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true);
const total = ref(0);
const tableData = ref([])
const formInline =ref({
  name: ''
});
// 对话框控制
const dialogVisible = ref(false)
const mode = ref('add') // add/edit/view
const formData = ref({
  id: null,
  name: '',
  sex: null,
  avatar: '',
  address: '',
  profile: '',
  field: '',
  certify: '',
  levelId: null,
  levelName: ''
})
// 添加选中的行数据
const selectedRows = ref([]);
const uploadRef = ref(null)

// 定义等级选项
const levelOptions = ref([
  { id: 1, name: '国家一级咨询师' },
  { id: 2, name: '国家二级咨询师' },
  { id: 3, name: '国家三级咨询师' }
  // 添加更多等级选项
])
const handleSuccess = (response) => {
  if (response.code === 1) {
    formData.value.avatar = 'http://localhost:8080' + response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请重试')
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleImageError = (e) => {
  e.target.style.display = 'none'
}
// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
})

onMounted(() => {
  search();
})
const search=async ()=>{
  const restult = await queryAllConsultant(currentPage.value,pageSize.value,formInline.value.name)
  console.log(restult)
  if(restult.code){
    tableData.value = restult.data.rows;
    total.value = restult.data.total
  }else{
    ElMessage.error(restult.msg)
  }
}
// 通用提交处理
const handleSubmit = () => {
  if (mode.value === 'add') {
    handleAddSubmit()
  } else if (mode.value === 'edit') {
    handleEditSubmit()
  }
}
// 提交添加
const handleAddSubmit = async () => {
  try {
    const result = await addConsultant(formData.value);
    if (result.code === 1) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '添加失败');
    }
  } catch (error) {
    ElMessage.error('添加请求失败');
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  try {
    const result = await updateConsultant(formData.value);
    if (result.code === 1) {
      ElMessage.success('更新成功');
      dialogVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新请求失败')
  }
}

// 打开添加对话框
const openAddDialog = () => {
  mode.value = 'add'
  formData.value = {
    id: null,
    name: '',
    sex: null,
    avatar: '',
    address: '',
    profile: '',
    field: '',
    certify: '',
    levelId: null,
    levelName: ''
  }
  dialogVisible.value = true
}



// 打开编辑对话框
const openEditDialog = (row) => {

  mode.value = 'edit'
  formData.value = {
    ...row,

    levelId:row.levelId
  }
  dialogVisible.value = true
}

// 打开详情对话框
const openViewDialog = (row) => {
  mode.value = 'view'
  formData.value = {
    ...row,
    levelId: row.levelId
  }
  dialogVisible.value = true
}


// 模式映射配置
const modeMap = reactive({
  add: { name: '添加咨询师', submit: handleAddSubmit },
  edit: { name: '编辑咨询师', submit: handleEditSubmit },
  view: { name: '咨询师详情详情' }
})


const handleDelete = async (idOrRows) => {
  // 统一处理为数组
  let ids = []
  // 数据类型转换逻辑
  if (typeof idOrRows === 'number') {
    ids = [idOrRows]
  } else if (Array.isArray(idOrRows)) {
    ids = idOrRows.map(item => Number(item.id))
  } else {
    ids = selectedRows.value.map(item => Number(item.id))
  }

  try {
    await ElMessageBox.confirm('确定删除选中数据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await deleteConsultant(ids)
    if (result.code === 1) {
      ElMessage.success('删除成功')
      // 清空选中项
      selectedRows.value = []
      search()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    console.log('取消删除')
  }
}

const handleSizeChange = (val) => {
  search()
}
const handleCurrentChange = (val) => {
  search()
}
</script>

<template>
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="咨询师姓名">
      <el-input v-model="formInline.name" placeholder="请输入咨询师姓名" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">搜索</el-button>
      <el-button type="primary" @click="openAddDialog">+添加咨询师</el-button>
      <el-button type="danger" @click="handleDelete">-批量删除</el-button>
    </el-form-item>
  </el-form>


  <el-table :data="tableData" border style="width: 100%"  @selection-change="val => selectedRows = val">
    <el-table-column type="selection"/>
    <el-table-column prop="id" label="id"/>
    <el-table-column prop="name" label="姓名"/>
    <el-table-column prop="sex" label="性别">
      <template #default="scope">
        {{ scope.row.sex === 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column prop="levelName" label="等级">
      <template #default="scope">
        {{ scope.row.consultantLevel ? scope.row.consultantLevel.levelName : '无' }}
      </template>
    </el-table-column>
    <el-table-column prop="avatar" label="头像">
      <template #default="scope">
        <div class="image-container">
          <img
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              @error="handleImageError"
              :alt="scope.row.name"
          >
          <div v-else class="image-placeholder">
            <el-icon><Picture /></el-icon>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="field" label="擅长领域"/>
    <el-table-column prop="address" label="地址"/>
    <el-table-column prop="profile" label="简介"/>
    <el-table-column prop="certify" label="是否认证">
      <template #default="scope">
    <span :style="{ color: scope.row.certify === '已认证' ? '#409eff' : 'red' }">
      {{ scope.row.certify }}
    </span>
      </template>
    </el-table-column>


    <el-table-column label="操作" width="280px">
      <template #default="scope">
        <el-button type="warning" size="mini"  @click="openViewDialog(scope.row)">详情</el-button>
        <el-button type="primary" size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  <!-- 通用对话框 -->
  <el-dialog
      v-model="dialogVisible"
      :title="modeMap[mode].title"
      width="40%"
  >
    <el-form
        :model="formData"
        label-width="100px"
        :disabled="mode === 'view'"
    >
      <!-- 查看模式显示ID和创建时间 -->
      <template v-if="mode === 'view'">
        <el-form-item label="FM ID">
          <el-input v-model="formData.id" readonly />
        </el-form-item>
      </template>

      <!-- 公共字段 -->
      <el-form-item label="姓名" prop="name" :rules="formRules.name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="formData.sex">
          <el-option label="男" value="1"/>
          <el-option label="女" value="0"/>
        </el-select>
      </el-form-item>

      <el-form-item label="等级" prop="levelId">
        <el-select v-model="formData.levelId">
          <el-option
              v-for="level in levelOptions"
              :key="level.id"
              :label="level.name"
              :value="level.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="/api/img/upload"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
            :before-upload="beforeUpload"
        >
          <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="擅长领域" prop="field">
        <el-input v-model="formData.field" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="formData.address" />
      </el-form-item>
      <el-form-item label="简介" prop="profile">
        <el-input v-model="formData.profile" />
      </el-form-item>
      <el-form-item label="是否认证" prop="certify">
        <el-select v-model="formData.certify">
          <el-option label="已认证" value="已认证"/>
          <el-option label="未认证" value="未认证"/>
        </el-select>
      </el-form-item>


    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button
          v-if="mode !== 'view'"
          type="primary"
          @click="handleSubmit">确认
      </el-button>
    </template>
  </el-dialog>




  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                 :page-sizes="[10, 20, 30, 40]" :size="size" :disabled="disabled" :background="background"
                 layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                 @current-change="handleCurrentChange" />

</template>
<style scoped>
/* 全局边距调整 */
.demo-form-inline {
  margin-bottom: 20px;
}

/* 表单元素间距调整 */
.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
  margin-right: 10px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 按钮组间距 */
.el-button + .el-button {
  margin-left: 12px;
}

/* 表格调整 */
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 分页组件调整 */
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 对话框表单样式 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 上传组件调整 */
.el-upload {
  margin-top: 8px;
}

/* 对话框底部按钮间距 */
.el-dialog__footer .el-button:not(:last-child) {
  margin-right: 12px;
}

/* 操作列按钮紧凑布局 */
.el-table-column--operation .el-button {
  margin: 4px;
  padding: 7px 12px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
/* 统一图片容器尺寸 */
.image-container {
  width: 100px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 修正真实图片样式 */
.el-table .cell img {
  width: 100%;
  height: 100%;
  object-fit: contain;  /* 保持比例填充 */
}

/* 调整占位符为绝对定位 */
.image-placeholder {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

/* 添加父级对齐容器 */
.el-table__cell > .cell {
  display: flex !important;
  justify-content: center;
  min-height: 62px; /* 包含边框高度 */
}

/* 统一悬停状态容器 */
.image-container:hover {
  transform: scale(1.8);
  z-index: 1000;
  transition: all 0.3s ease;
}

</style>